package com.foreverwin.mes.so.serviceext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.core.utils.SpringUtil;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Bom;
import com.foreverwin.mes.meapi.model.BomComponent;
import com.foreverwin.mes.meapi.service.BomService;
import com.sap.me.activity.ActivityRuntimeType;
import com.sap.me.activity.ExecutionType;
import com.sap.me.activity.ServiceExtension;
import com.sap.me.common.ObjectReference;
import com.sap.me.demand.CreateShopOrderRequest;
import com.sap.me.extension.Services;
import com.sap.me.productdefinition.ItemBasicConfiguration;
import com.sap.me.productdefinition.ItemConfigurationServiceInterface;
import com.visiprise.globalization.util.DateTimeInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

/**
 * MES工单创建服务扩展
 *
 * @author Syngna
 * @date 2020/2/25 21:18
 */
@ExecutionType(ActivityRuntimeType.SYNC)
public class CreateShopOrderExtension extends ServiceExtension<Object> {
    private final Logger logger = LoggerFactory.getLogger(CreateShopOrderExtension.class);

    private BomService bomService;

    @Override
    public void execute(Object request) throws Exception {
        if (request instanceof CreateShopOrderRequest) {
            execute((CreateShopOrderRequest) request);
        }
    }

    public void execute(CreateShopOrderRequest createShopOrderRequest) throws Exception {
        logger.info("create shop order service extension start");
        bomService = SpringUtil.getBean(BomService.class);
        String site = com.sap.me.frame.service.CommonMethods.getSite();
        String shopOrder = createShopOrderRequest.getShopOrder();
        String plannedItemRef = createShopOrderRequest.getPlannedItemRef();
        ItemConfigurationServiceInterface itemConfigurationServiceInterface = Services.getService("com.sap.me.productdefinition", "ItemConfigurationService", site);
        ItemBasicConfiguration itemBasicConfiguration = itemConfigurationServiceInterface.findItemConfigurationByRef(new ObjectReference(plannedItemRef));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("PlannedOrder", createShopOrderRequest.getShopOrder());
        jsonObject.put("ProductionPlant", site);
        jsonObject.put("QuantityIsFixed", "Create"); // Create创建，Update修改，Delete删除
        jsonObject.put("Material", StringUtils.trimHandle(createShopOrderRequest.getPlannedItemRef()));
        jsonObject.put("TotalQuantity", createShopOrderRequest.getQuantityToBuild());
        jsonObject.put("BaseUnit", itemBasicConfiguration.getUnitOfMeasurement());
        DateTimeInterface plannedStartDateTimeInterface = createShopOrderRequest.getPlannedStartDate();
        DateTimeInterface plannedEndDateTimeInterface = createShopOrderRequest.getPlannedCompletionDate();
        jsonObject.put("PlndOrderPlannedStartDate", plannedStartDateTimeInterface == null ? null : "/Date(" + plannedStartDateTimeInterface.getTimeInMillis() + ")/");
        jsonObject.put("PlndOrderPlannedEndDate", plannedEndDateTimeInterface == null ? null : "/Date(" + plannedEndDateTimeInterface.getTimeInMillis() + ")/");

        String bomRef = createShopOrderRequest.getPlannedBomRef();
        Bom bom = null;
        if (StringUtils.notBlank(bomRef) && "H".equals(bomRef.split(",")[2])) {
            bom = bomService.getBomInfo(site, bomRef);
        }
        if (bom != null && bom.getBomComponentList() != null && bom.getBomComponentList().size() > 0) {
            JSONObject componentObj = new JSONObject();
            JSONArray componentJSONArray = new JSONArray();
            jsonObject.put("to_PlannedOrderComponent", componentObj);
            for (BomComponent bomComponent : bom.getBomComponentList()) {
                ItemBasicConfiguration componentItem = itemConfigurationServiceInterface.findItemConfigurationByRef(new ObjectReference(plannedItemRef));
                JSONObject componentJson = new JSONObject();
                componentJson.put("BillOfMaterialItemNumber", bomComponent.getSequence()); // ME工单BOM->组件->顺序
                componentJson.put("Material", StringUtils.trimHandle(bomComponent.getComponentGbo())); // ME的工单BOM->组件->物料
                componentJson.put("BaseUnit", componentItem == null ? "" : componentItem.getUnitOfMeasurement()); // ME的工单BOM->组件->基本单位
                componentJson.put("RequiredQuantity", new BigDecimal(bomComponent.getQty()).multiply(createShopOrderRequest.getQuantityToBuild())); // ME的工单BOM->组件->基本用量*工单数量
                componentJSONArray.add(componentJson);
            }
            componentObj.put("results", componentJSONArray);
        }

        logger.info("send shop order to erp : " + jsonObject.toJSONString());
    }
}
